package com.covid.lab3.controller;

import com.covid.lab3.model.RegionStats;
import com.covid.lab3.service.DataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class controller {

    private  DataService dataService;
    public controller(DataService dataService) {

        this.dataService = dataService;
    }

    @GetMapping("/")
    public String Index(Model model,String country){
        List<RegionStats> regionStatsList;

        if (country == null)
            regionStatsList = dataService.getAllRegionStats();

        else{
            regionStatsList = (List<RegionStats>) dataService.getAllRegionStats()
                    .parallelStream()
                    .filter(locationStates -> locationStates.getCountry().equals(country))
                    .collect(Collectors.toList());
        }

        int totalCases = regionStatsList.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int localFromPrevDay = regionStatsList.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStatsList", regionStatsList);
        model.addAttribute("country", country);
        model.addAttribute("totalCases", totalCases);
        model.addAttribute("localFromPrevDay", localFromPrevDay);
        model.addAttribute("localDate", LocalDate.now());

        return "index";
    }

}
